using System;
using System.Windows.Forms;
using BizTalk.BuildGenerator.MetaData;
using BizTalk.BuildGenerator.UI.Navigation;

namespace BizTalk.BuildGenerator.UI.UserControls
{
    public partial class ApplicationDescriptionControl : UserControl, IWizardControl
    {
        private GenerationArgs _args;

        public ApplicationDescriptionControl()
        {
            InitializeComponent();
        }

        private void ApplicationDescriptionControlLoad(object sender, EventArgs e)
        {
            if (DesignMode) return;
            ApplicationsComboBox.Items.AddRange(BizTalkHelper.GetApplications().ToArray());
            SetupControls();
        }

        private void SetupControls()
        {
            if (_args == null)
                return;
            if (_args.ApplicationDescription == null)
                return;
            if (_args.ApplicationDescription.Name == null)
                return;

            var index = ApplicationsComboBox.FindString(_args.ApplicationDescription.Name);
            if (index >= 0)
                ApplicationsComboBox.SelectedIndex = index;

            if (_args.OutputFolder == null)
                return;
            OutputDirectoryTextBox.Text = _args.OutputFolder;

            if (string.IsNullOrEmpty(_args.SolutionPath))
                return;
            SourceCodeRootTextBox.Text = _args.SolutionPath;
        }

        public ApplicationDescription GetDescription()
        {
            return BizTalkHelper.DescribeApplication((string) ApplicationsComboBox.SelectedItem);
        }

        public void RegisterArgs(GenerationArgs args)
        {
            _args = args;
            SetupControls();
        }

        #region IWizardControl Members

        public MoveNextResult MoveNext()
        {
            _args.ApplicationDescription = GetDescription();
            _args.OutputFolder = OutputDirectoryTextBox.Text;
            _args.SolutionPath = SourceCodeRootTextBox.Text;
            
            var result = new MoveNextResult {CanMoveNext = true};
            return result;
        }

        #endregion

        private void BrowseDirectoryButtonClick(object sender, EventArgs e)
        {
            var dr = folderBrowserDialog.ShowDialog();
            if (dr == DialogResult.OK)
                OutputDirectoryTextBox.Text = folderBrowserDialog.SelectedPath;
        }

        private void BrowseSourceCodeFolderButtonClick(object sender, EventArgs e)
        {
            var dr = openFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
                SourceCodeRootTextBox.Text = openFileDialog1.FileName;
        }
    }
}